<template>
  <div class="reset-password-container">
    <!-- 添加logo -->
    <div class="login-logo">
      <img src="../logo/1.png" alt="Logo" class="logo-img">
    </div>

    <el-card class="reset-password-card">
      <div class="card-header">
        <h2>重置密码</h2>
        <p>请填写以下信息重置您的密码</p>
      </div>
      <el-form ref="resetPasswordForm" :model="form" :rules="rules" class="reset-password-form">
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入你的账号"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input type="password" v-model="form.newPassword" placeholder="请输入你的新密码"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入你的邮箱"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="verifyCode">
          <el-input v-model="form.verifyCode" placeholder="验证码">
            <template #append>
              <el-button @click="getVerifyCode" :disabled="countdown > 0">{{ countdown > 0 ? `${countdown}秒后重新发送` :
                '发送验证码' }}</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item class="form-actions">
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
// 添加request导入
import request from '@/utils/request';

const router = useRouter();
const form = ref({
  username: '',
  newPassword: '',
  email: '',
  verifyCode: ''
});

const rules = ref({
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
});

const resetPasswordForm = ref(null);
const countdown = ref(0);

const submitForm = async () => {
  try {
    await resetPasswordForm.value.validate();

    // 构造提交数据对象
    const submitData = {
      username: form.value.username,
      password: form.value.newPassword,
      email: form.value.email,
      code: form.value.verifyCode
    };

    // 打印提交内容到控制台
    console.log('提交的重置密码数据:', submitData);

    // 发送请求 - 修复参数传递方式
    const response = await request.get('/users/forgetPassword', {
      params: {
        code: form.value.verifyCode,
        email: form.value.email,
        password: form.value.newPassword,
        username: form.value.username
      }
    });

    // 修复响应判断逻辑 - 同时修正消息组件使用错误
    if (response.code === 200) {
      ElMessage.success({
        message: '密码重置成功',
        duration: 3000
      });
      // 延迟跳转确保用户看到成功提示
      setTimeout(() => {
        router.push('/login');
      }, 1500);
    } else {
      ElMessage.error(response.data.msg || '密码重置失败，请重试');
    }
  } catch (error) {
    // 详细错误日志，用于调试
    console.error('重置密码错误详情:', error);

    // 错误处理 - 更精确的错误类型判断
    if (error.response) {
      // 服务器返回了响应但状态码非2xx
      const status = error.response.status;
      const errorMsg = error.response.data?.msg || `服务器错误 (${status})`;
      ElMessage.error(errorMsg);
    } else if (error.request) {
      // 请求已发送但无响应
      ElMessage.error('请求超时，请检查网络连接');
    } else if (error.name === 'ValidationError') {
      // 表单验证错误
      ElMessage.error('请完善表单信息');
    } else {
      // 其他错误
      ElMessage.error('操作失败: ' + error.message);
    }
  }
};

const getVerifyCode = () => {
  if (!form.value.username) {
    ElMessage.warning('请先输入账号');
    return;
  }
  if (!form.value.email) {
    ElMessage.warning('请先输入邮箱');
    return;
  }

  // 开始倒计时
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);

  const codeVO = { email: form.value.email, mailTitle: 'SEND_CODE_REGISTRATION' };
  console.log('发送验证码请求参数:', { codeVO });
  request.post('/users/sendCode', {
    email: form.value.email,
    mailTitle: 'SEND_CODE_FORGETPASSWORD'
  })
    .then((response) => {
      console.log('验证码发送成功响应:', response.data);
      ElMessageBox.alert('验证码已发送至邮箱', '系统提示', {
        confirmButtonText: '确定',
        type: 'info',
        center: true
      });
    })
    .catch(error => {
      clearInterval(timer);
      countdown.value = 0;
      console.error('验证码发送失败:', error.response ? error.response.data : error.message);
      ElMessage.error('验证码发送失败: ' + (error.response?.data?.message || '请稍后重试'));
    });
};

const goBack = () => {
  router.push('/login');
};
</script>

<style scoped>
/* 替换原有背景样式，使用登录页面的动态背景 */
.reset-password-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  position: relative;
  overflow: hidden;
  padding: 20px;
}

.reset-password-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  /* 四色渐变方案 - 电力系统专业蓝 */
  background: linear-gradient(135deg, #0a2463 0%, #2980b9 35%, #3e92cc 65%, #5dade2 100%);
  z-index: -2;
  /* 平滑过渡动画 */
  animation: gradientShift 15s ease infinite;
  background-size: 400% 400%;
}

.reset-password-container::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  /* 白色漩涡光圈效果 */
  background-image:
    radial-gradient(circle at 50% 50%, rgba(255, 255, 255, 0.5) 0%, rgba(255, 255, 255, 0) 60%),
    radial-gradient(circle at 30% 30%, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0) 40%),
    radial-gradient(circle at 70% 70%, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0) 40%);
  z-index: -1;
  /* 漩涡旋转动画 */
  animation: vortexRotate 20s linear infinite;
}

/* 渐变背景动画 */
@keyframes gradientShift {
  0% {
    background-position: 0% 50%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}

/* 漩涡旋转动画 */
@keyframes vortexRotate {
  0% {
    transform: rotate(0deg) scale(1);
    background-position: 50% 50%, 30% 30%, 70% 70%;
  }

  50% {
    transform: rotate(180deg) scale(1.1);
    background-position: 60% 40%, 40% 60%, 80% 20%;
  }

  100% {
    transform: rotate(360deg) scale(1);
    background-position: 50% 50%, 30% 30%, 70% 70%;
  }
}

.reset-password-card {
  width: 100%;
  max-width: 500px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.12);
  border-radius: 12px;
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.reset-password-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
}

.card-header {
  text-align: center;
  padding: 30px 24px;
  background-color: #ffffff;
  border-bottom: 1px solid #f5f5f5;
}

.card-header h2 {
  margin: 0 0 12px;
  color: #1d2129;
  font-size: 24px;
  font-weight: 600;
}

.card-header p {
  margin: 0;
  color: #4e5969;
  font-size: 14px;
  line-height: 1.5;
}

.reset-password-form {
  padding: 30px 24px;
  background-color: #ffffff;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  color: #4e5969;
  font-weight: 500;
}

.el-input {
  border-radius: 6px;
  border-color: #dcdfe6;
  transition: border-color 0.2s, box-shadow 0.2s;
}

.el-input:focus-within {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.form-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 24px;
}

.el-button {
  padding: 12px 20px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.el-button:not(.el-button--primary):hover {
  color: #409eff;
  border-color: #c6e2ff;
}

/* 响应式调整 */
@media (max-width: 576px) {
  .form-actions {
    flex-direction: column;
    gap: 12px;
  }

  .el-button {
    width: 100%;
  }
}

/* 添加logo样式 */
.login-logo {
  position: absolute;
  top: 25px;
  left: 25px;
  z-index: 1;
}

.logo-img {
  max-width: 180px;
  max-height: 120px;
  width: auto;
  height: auto;
  object-fit: contain;
}

/* 调整卡片位置避免重叠 */
.reset-password-card {
  margin-top: 60px;
}
</style>